package com.fw.ui.view.settings.usercontrol.merchantuser.event;

import static org.springframework.beans.factory.config.BeanDefinition.SCOPE_PROTOTYPE;

import java.io.Serializable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.fw.service.bean.ErrorBean;
import com.fw.service.merchantuser.bean.MerchantUserBean;
import com.fw.ui.ApplicationUI;
import com.fw.ui.bao.MerchantUserBAO;
import com.fw.ui.bao.MessageBAO;
import com.fw.ui.util.SessionInfoUtils;
import com.fw.ui.util.UICommonUtils;
import com.fw.ui.util.VaadinApplicationObjectSupport;
import com.fw.ui.view.common.ConfirmDialogWindow;
import com.fw.ui.view.event.AbstractButtonClickListener;
import com.fw.ui.view.settings.usercontrol.merchantuser.CreateMerchantUserView;
import com.vaadin.ui.Button.ClickEvent;

@Component
@Scope(SCOPE_PROTOTYPE)
public class CreateMerchantUserSaveButtonClickListener extends AbstractButtonClickListener {

    private static final long serialVersionUID = 482478998438351054L;

    @Autowired
    protected transient VaadinApplicationObjectSupport app;
    @Autowired
    private MerchantUserBAO merchantUserBAO;
    @Autowired
    private MessageBAO messageBAO;
    @Autowired
    private UICommonUtils uiCommonUtils;
    @Autowired
    private SessionInfoUtils sessionInfoUtils;

    @SuppressWarnings("unchecked")
    @Override
    public Map<String, Object> click(ClickEvent event) throws Exception {
	CreateMerchantUserView createMerchantUserView = (CreateMerchantUserView) this.getBasedComponent();

	String selected = (String) createMerchantUserView.getOgMerchantOrParentId().getValue();
	Long merchantId = (Long) createMerchantUserView.getCbbMerchant().getValue();
	String merchantID = (String) createMerchantUserView.getCbbMerchant().getItemCaption(merchantId);
	Long serviceId = (Long) createMerchantUserView.getCbbService().getValue();
	String serviceID = (String) createMerchantUserView.getCbbService().getItemCaption(serviceId);
	Long parentId = (Long) createMerchantUserView.getCbbParent().getValue();
	String parentID = (String) createMerchantUserView.getCbbParent().getItemCaption(parentId);
	String username = createMerchantUserView.getTxtUsername().getValue();
	String email = createMerchantUserView.getTxtEmail().getValue();
	String name = createMerchantUserView.getTxtName().getValue();
	Long roleId = (Long) createMerchantUserView.getCbbGroup().getValue();
	String roleName = (String) createMerchantUserView.getCbbGroup().getItemCaption(roleId);

	MerchantUserBean merchantUserBean = new MerchantUserBean();
	if (createMerchantUserView.getMerchantOption().equals(selected)) {
	    merchantUserBean.setMerchantID(merchantID);
	    merchantUserBean.setServiceID(serviceID);
	} else if (createMerchantUserView.getParentOption().equals(selected)) {
	    merchantUserBean.setParentID(parentID);
	}
	merchantUserBean.setEmail(email);
	merchantUserBean.setUsername(username);
	merchantUserBean.setName(name);
	merchantUserBean.setRole(roleName);

	ApplicationUI applicationUI = (ApplicationUI) createMerchantUserView.getUI();
	sessionInfoUtils.setSessionInfoDetails(merchantUserBean, applicationUI.getAuthenticationBean(), applicationUI.getLocale());

	Map<String, Serializable> mapResult = this.merchantUserBAO.createMerchantUser(merchantUserBean);
	Map<String, Object> result = new HashMap<String, Object>();
	if (mapResult != null) {
	    List<ErrorBean> errorBeans = (List<ErrorBean>) mapResult.get(List.class.getName() + "." + ErrorBean.class.getName());
	    MerchantUserBean resultMerchantUserBean = (MerchantUserBean) mapResult.get(MerchantUserBean.class.getName());
	    if (errorBeans != null && !errorBeans.isEmpty()) {
		result.put(MessageBAO.MESSAGE_WARNING_TYPE, errorBeans);
	    } else {
		if (resultMerchantUserBean != null && resultMerchantUserBean.getId() != null) {

		    uiCommonUtils.clearAllUIComponentWithPrefixDefaultValue(createMerchantUserView, null);
		    createMerchantUserView.getOgMerchantOrParentId().setValue(createMerchantUserView.getMerchantOption());

		    String title = messageBAO.getMessage("message.dialog.title.info");
		    String[] params = new String[] { resultMerchantUserBean.getPassword() };
		    String content = messageBAO.getMessageWithParams(
			    "com.fw.ui.view.settings.usercontrol.merchantuser.CreateMerchantUserView.message.created", params);
		    String okCaption = messageBAO.getMessage("application.button.ok.caption");

		    ConfirmDialogWindow.createConfirmDialog(createMerchantUserView.getUI(), title, content, okCaption, null, "150px",
			    "500px");

		    return null;
		} else {
		    result.put(MessageBAO.MESSAGE_WARNING_TYPE,
			    "com.fw.ui.view.settings.usercontrol.merchantuser.CreateMerchantUserView.message.failed");
		}
	    }
	} else {
	    result.put(MessageBAO.MESSAGE_WARNING_TYPE, "message.error.common");
	}
	return result;
    }

    @Override
    public boolean validate(ClickEvent event) {
	CreateMerchantUserView createMerchantUserView = (CreateMerchantUserView) this.getBasedComponent();
	try {

	    uiCommonUtils.clearAllUIComponentNoInputFieldWithPrefix(createMerchantUserView);

	    boolean merchantValid = createMerchantUserView.getCbbMerchant().isValid();
	    boolean parentValid = createMerchantUserView.getCbbParent().isValid();
	    boolean usernameValid = createMerchantUserView.getTxtUsername().isValid();
	    boolean emailValid = createMerchantUserView.getTxtEmail().isValid();
	    boolean nameValid = createMerchantUserView.getTxtName().isValid();
	    boolean groupValid = createMerchantUserView.getCbbGroup().isValid();

	    if (merchantValid && parentValid && usernameValid && emailValid && nameValid && groupValid) {
		Boolean isUnique = this.merchantUserBAO.checkUniqueUsername(createMerchantUserView.getTxtUsername().getValue());
		if (isUnique == null || !isUnique.booleanValue()) {
		    createMerchantUserView.getTxtUsername().addStyleName("v-textfield-error");
		    createMerchantUserView
			    .getLblUsernameValidateMessage()
			    .setValue(
				    this.messageBAO
					    .getMessage("com.fw.ui.view.settings.usercontrol.merchantuser.CreateMerchantUserView.message.username.exist"));
		    createMerchantUserView.getRow1Validate().setVisible(true);
		    return false;
		}
		return true;
	    } else {

		if (!merchantValid) {
		    createMerchantUserView.getCbbMerchant().addStyleName("v-textfield-error");
		    if (createMerchantUserView.getCbbMerchant().getErrorMessage() != null) {
			createMerchantUserView.getLblMerchantOrParentValidateMessage().setValue(
				createMerchantUserView.getCbbMerchant().getErrorMessage().getFormattedHtmlMessage());
		    }
		    createMerchantUserView.getRow1Validate().setVisible(true);
		}

		if (!parentValid) {
		    createMerchantUserView.getCbbParent().addStyleName("v-textfield-error");
		    if (createMerchantUserView.getCbbParent().getErrorMessage() != null) {
			createMerchantUserView.getLblMerchantOrParentValidateMessage().setValue(
				createMerchantUserView.getCbbParent().getErrorMessage().getFormattedHtmlMessage());
		    }
		    createMerchantUserView.getRow1Validate().setVisible(true);
		}

		if (!usernameValid) {
		    createMerchantUserView.getTxtUsername().addStyleName("v-textfield-error");
		    if (createMerchantUserView.getTxtUsername().getErrorMessage() != null) {
			createMerchantUserView.getLblUsernameValidateMessage().setValue(
				createMerchantUserView.getTxtUsername().getErrorMessage().getFormattedHtmlMessage());
		    }
		    createMerchantUserView.getRow2Validate().setVisible(true);
		} else {
		    Boolean isUnique = this.merchantUserBAO.checkUniqueUsername(createMerchantUserView.getTxtUsername().getValue());
		    if (isUnique == null || !isUnique.booleanValue()) {
			createMerchantUserView.getTxtUsername().addStyleName("v-textfield-error");
			createMerchantUserView
				.getLblUsernameValidateMessage()
				.setValue(
					this.messageBAO
						.getMessage("com.fw.ui.view.settings.usercontrol.merchantuser.CreateMerchantUserView.message.username.exist"));
			createMerchantUserView.getRow2Validate().setVisible(true);
		    }
		}

		if (!emailValid) {
		    createMerchantUserView.getTxtEmail().addStyleName("v-textfield-error");
		    if (createMerchantUserView.getTxtEmail().getErrorMessage() != null) {
			createMerchantUserView.getLblEmailValidateMessage().setValue(
				createMerchantUserView.getTxtEmail().getErrorMessage().getFormattedHtmlMessage());
		    }
		    createMerchantUserView.getRow3Validate().setVisible(true);
		}

		if (!nameValid) {
		    createMerchantUserView.getTxtName().addStyleName("v-textfield-error");
		    if (createMerchantUserView.getTxtName().getErrorMessage() != null) {
			createMerchantUserView.getLblNameValidateMessage().setValue(
				createMerchantUserView.getTxtName().getErrorMessage().getFormattedHtmlMessage());
		    }
		    createMerchantUserView.getRow4Validate().setVisible(true);
		}

		if (!groupValid) {
		    createMerchantUserView.getCbbGroup().addStyleName("v-filterselect-error");
		    if (createMerchantUserView.getCbbGroup().getErrorMessage() != null) {
			createMerchantUserView.getLblGroupValidateMessage().setValue(
				createMerchantUserView.getCbbGroup().getErrorMessage().getFormattedHtmlMessage());
		    }
		    createMerchantUserView.getRow5Validate().setVisible(true);
		}
	    }

	} catch (Exception e) {
	    e.printStackTrace();
	    return false;
	}
	return false;
    }

}
